/**
 *
 *  You can modify and use this source freely
 *  only for the development of application related Live2D.
 *
 *  (c) Live2D Inc. All rights reserved.
 */

// ============================================================
// ============================================================
//  class PlatformManager     extend IPlatformManager
// ============================================================
// ============================================================
export function PlatformManager() {

}

// ============================================================
//    PlatformManager # loadBytes() 加载一个二进制文件
// ============================================================
PlatformManager.prototype.loadBytes = function(path/* String*/, callback) {
  var request = new XMLHttpRequest()
  request.open('GET', path, true)
  request.responseType = 'arraybuffer'
  request.onload = function() {
    switch (request.status) {
      case 200:
        callback(request.response)
        break
      default:
        console.error('HTTP GET Failed to load (' + request.status + ') : ' + path)
        break
    }
  }
  request.send(null)
  // return request;
}

// ============================================================
//    PlatformManager # loadString() 加载字符串文件
// ============================================================
PlatformManager.prototype.loadString = function(path/* String*/) {
  this.loadBytes(path, function(buf) {
    return buf
  })
}

// ============================================================
//    PlatformManager # loadLive2DModel()
// ============================================================
PlatformManager.prototype.loadLive2DModel = function(path/* String*/, callback) {
  let model = null

  // load moc
  this.loadBytes(path, function(buf) {
    model = window.Live2DModelWebGL.loadModel(buf)
    callback(model)
  })
}

// ============================================================
//    PlatformManager # parseFromBytes(buf) 将二进制文件转化为json

// ============================================================
PlatformManager.prototype.jsonParseFromBytes = function(buf) {
  let jsonStr

  const bomCode = new Uint8Array(buf, 0, 3)
  if (bomCode[0] === 239 && bomCode[1] === 187 && bomCode[2] === 191) {
    jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf, 3))
  } else {
    jsonStr = String.fromCharCode.apply(null, new Uint8Array(buf))
  }

  const jsonObj = JSON.parse(jsonStr)

  return jsonObj
}

// ============================================================
//    PlatformManager # log()
// ============================================================
PlatformManager.prototype.log = function(txt/* String*/) {
  console.log(txt)
}

